package com.example.rbac.controller.restful;

import com.example.rbac.Exception.ResultErrorException;
import com.example.rbac.entity.*;
import com.example.rbac.entity.defefult.Result;
import com.example.rbac.eunm.date;
import com.example.rbac.service.MenuService;
import com.example.rbac.service.RoleMenuService;
import com.example.rbac.service.RoleService;
import com.example.rbac.service.UserService;
import com.example.rbac.uitls.CollectionUtils;
import com.example.rbac.uitls.ResultUtil;
import com.example.rbac.uitls.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2017/10/15.
 */
@RestController
@RequestMapping("/Menu")
public class MenuRestController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 左侧根目录数据
     *
     * @return
     */
    @GetMapping("/getMenuList")
    public Result<Menu> getMenuList() {
        User token = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = token.getId();
        //根据用户id查询对应的角色id
        List<String> roleIds = userService.findRoleByUserId(userId);
        //根据角色获取对应的权限,添加到shiro的权限验证
        List<String> menuIdList = menuService.findMenuByRoleId(roleIds);
        List<Menu> menuList = menuService.findMenuByMenuId(menuIdList);
        List<Menu> menuLists = CollectionUtils.ListMenu(menuList, "0");
        return ResultUtil.success(menuLists);
    }


    /**
     * 角色里的栏目树结构
     *
     * @return
     */
    @GetMapping("/getMenuTreeList")
    public List<Map<String, Object>> getMenuTreeList() {
        List<Menu> menuList = menuService.findList();
        List<Map<String, Object>> mapList = Lists.newLinkedList();
        for (Menu menu : menuList) {
            Map<String, Object> map = Maps.newLinkedHashMap();
            map.put("id", menu.getId());
            map.put("pId", menu.getPid());
            map.put("name", menu.getName());
            map.put("rootPId", menu.getPid() == "0" ? menu.getPid() : "");
            map.put("checked", "1".equals(menu.getState()) ? "true" : "false");
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 菜单所有数据
     *
     * @return
     */
    @GetMapping("/getList")
    public Result<Menu> getList() {
        List<Menu> menuList = CollectionUtils.pushOneGroup(menuService.findList(), "0");
        for (Menu m : menuList) {
            for (int i = 1; i < m.getLevel(); i++) {
                m.setName("|-" + m.getName());
            }
        }
        return ResultUtil.success(menuList);
    }

    @GetMapping(value = "/deleteMenu", produces = {"text/javascript;charset=UTF-8"})
    public Result<Integer> deleteMenu(String id) {
        return ResultUtil.success(menuService.deleteMenuById(id));
    }


    @GetMapping("/getRoot")
    public Result getRoot(String url) {
        Menu menu = menuService.getMenuByUrl(url);
        List<Menu> list = CollectionUtils.getParents(menuService.findList(), menu.getPid());
        list.add(menu);
        return ResultUtil.success(list);
    }

    @RequiresPermissions("menu:edit")
    @GetMapping("/edit")
    public Result MenuAdd(String id) {
        Menu menu = null;
        if (StringUtils.isNotEmpty(id)) {
            menu = menuService.get(id);
        }
        return ResultUtil.success(menu);
    }


    @PostMapping("/save")
    public Result save(Menu menu) {
        //保存menu对象
        menu.setLevel(menu.getLevel() + 1);
        String id = UUID.randomUUID().toString().replace("-", "");
        menu.setId(id);
        int num = menuService.save(menu);
        //保存roleMenu
        List<Role> list = roleService.findList();
        List<String> roleIds = Lists.newArrayList();
        list.forEach((role -> {
            roleIds.add(role.getId());
        }));
        String i = date.YES.getVal();
        roleMenuService.insertByMenuId(menu.getId(), roleIds, date.NO.getVal());
        return ResultUtil.success(num);
    }


    @PostMapping("/updateBySort")
    public Result updateBySort(@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "sorts[]") String[] sorts) {
        try {
            List<Menu> list = Lists.newArrayList();
            for (int i = 0; i < ids.length; i++) {
                Menu menu = new Menu();
                menu.setId(ids[i]);
                menu.setSort(sorts[i]);
                list.add(menu);
            }
            Integer rst = menuService.updateBySort(list);
            return ResultUtil.success(menuService.updateBySort(list));
        } catch (ResultErrorException e) {
            return ResultUtil.erorr(404, e.toString());
        }
    }

    @GetMapping("/page")
    public Page getPager(Integer pageNum, Integer pageSize) {
        Page<Menu> menuList = new Page<Menu>();
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 5;
        }
        menuList = menuService.getPager(pageNum, pageSize);
        return menuList;
    }


}
